package com.gk.util
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;

	/**
	 *加载对象 （pic  swf 。。） 
	 * 
	 * <br/> 跨域加载图片，只能用Loader做容器  无法获取到bitmap
	 * @author Nestor
	 * 
	 */	
	public class LoadObject
	{
		private var okFun:Function;
		private var errorFun:Function;
		private var loader:Loader;
		private var isDomain:Boolean;
		/**
		 * 
		 * @param okFun (参数 dobj)
		 * @param errFun (参数  IOErrorEvent)
		 * @param isDomain 加载图片 是否跨域 
		 * 
		 */		
		public function LoadObject(url:String,okFun:Function,errFun:Function =null,isDomain:Boolean = false)
		{
			
			this.okFun = okFun;
			this.errorFun = errFun;
			this.isDomain = isDomain;
			
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,comHadnler);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
			if(isDomain){
				trace("Domain！！");
				var lc:LoaderContext = new LoaderContext(true);
				loader.load(new URLRequest(url),lc);
			}else{
				loader.load(new URLRequest(url));
			}
			
		}
		
		private function errorHandler(e:IOErrorEvent):void
		{
			if(Boolean(this.errorFun)){
				this.errorFun(e);
				this.errorFun = null;
			}
			clear();
		}
		
		private function comHadnler(e:Event):void
		{
			
			var dobj:DisplayObject =isDomain?loader:loader.contentLoaderInfo.content;
			if(Boolean(this.okFun)){
				this.okFun(dobj);
				this.okFun = null;
			}
			
			clear();
		}
		
		private function clear():void
		{
			// TODO Auto Generated method stub
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,comHadnler);
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,errorHandler);
		}		
		
	}
}